package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.user.vo.LoginRespVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author weiranyi
 * @description 针对表【user_info(用户表)】的数据库操作Service实现
 * @createDate 2022-12-15 11:56:44
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public LoginRespVo login(UserInfo userInfo, HttpServletRequest request) {
        // 1.查询数据库是否存在该用户
        String loginName = userInfo.getLoginName();
        String passwordEncrypt = MD5.encrypt(userInfo.getPasswd());

        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getLoginName, loginName)
                .eq(UserInfo::getPasswd, passwordEncrypt);
        UserInfo userInfoFromDB = this.getOne(queryWrapper);

        // 2.判断登录成功与否
        if (userInfoFromDB == null) {
            // 2.1 失败
            throw new GmallException(ResultCodeEnum.USER_PWD_INVAILD);
        }
        // 2.2 成功
        LoginRespVo respVo = new LoginRespVo();
        respVo.setUserId(userInfoFromDB.getId());
        respVo.setNickName(userInfoFromDB.getNickName());
        // 生成用户唯一标识
        String token = UUID.randomUUID().toString().replace("-", "");
        respVo.setToken(token);
        // token及ip信息 保存到redis中 [存储IP信息一定程度上防止登录信息被拷贝]
        String ipAddress = IpUtil.getIpAddress(request);
        userInfoFromDB.setIp(ipAddress);
        redisTemplate.opsForValue().set(
                RedisConst.LOGIN_USER + token,
                JSON.toJSONString(userInfoFromDB),
                RedisConst.LOGIN_USER_TTL,
                TimeUnit.DAYS
        );
        return respVo;
    }

    /**
     * 退出
     *
     * @param token
     */
    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConst.LOGIN_USER + token);
    }
}




